package com.xuecheng.filesystem.service;

import com.alibaba.fastjson.JSON;
import com.xuecheng.filesystem.dao.FileSystemRepository;
import com.xuecheng.framework.domain.filesystem.FileSystem;
import com.xuecheng.framework.domain.filesystem.response.FileSystemCode;
import com.xuecheng.framework.domain.filesystem.response.UploadFileResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import org.apache.commons.lang3.StringUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
public class FileSystemService {

    // private static final Logger LOGGER = LoggerFactory.getLogger(FileSystemService.class);
    private FileSystemRepository fileSystemRepository;

    @Autowired
    public FileSystemService(FileSystemRepository fileSystemRepository){
        this.fileSystemRepository = fileSystemRepository;
    }

    @Value("${xuecheng.fastdfs.tracker_servers}")
    private String tracker_servers;
    @Value("${xuecheng.fastdfs.connect_timeout_in_seconds}")
    private int connect_timeout_in_seconds;
    @Value("${xuecheng.fastdfs.network_timeout_in_seconds}")
    private int network_timeout_in_seconds;
    @Value("${xuecheng.fastdfs.charset}")
    private String charset;

    public UploadFileResult upload(MultipartFile multipartFile, String fileTag, String businessKey, String metadata) {
        if(multipartFile == null){
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
        }
        // 上传文件到fdfs
        String fileId = fafs_upload(multipartFile);
        // 创建文件信息对象
        FileSystem fileSystem = new FileSystem();
        fileSystem.setFileId(fileId);
        fileSystem.setFilePath(fileId);
        // 业务标识
        fileSystem.setBusinesskey(businessKey);
        // 标签
        fileSystem.setFiletag(fileTag);
        // 元数据
        if(StringUtils.isNotEmpty(metadata)){
            try {
                Map map = JSON.parseObject(metadata, Map.class);
                fileSystem.setMetadata(map);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        // 名称
        fileSystem.setFileName(multipartFile.getOriginalFilename());
        fileSystem.setFileSize(multipartFile.getSize());
        // 文件类型
        fileSystem.setFileType(multipartFile.getContentType());
        fileSystemRepository.save(fileSystem);
        return new UploadFileResult(CommonCode.SUCCESS, fileSystem);
    }

    // 上传文件到fdfs，返回文件id
    private String fafs_upload(MultipartFile file) {
        try {
            // 加载fafs的配置
            initFdfsConfig();
            // tracker client
            TrackerClient trackerClient = new TrackerClient();
            // trackerServer
            TrackerServer trackerServer = trackerClient.getConnection();
            // storeStorage
            StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
            // storage client
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storeStorage);
            // 上传文件
            byte[] bytes = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            // 文件扩展名
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            // 文件Id
            String file1 = storageClient1.upload_file1(bytes, extName, null);
            return file1;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return null;

    }

    // 加载fafds
    private void initFdfsConfig() {
        try {
            ClientGlobal.initByTrackers(tracker_servers);
            ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);
            ClientGlobal.setG_network_timeout(network_timeout_in_seconds);
            ClientGlobal.setG_charset(charset);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionCast.cast(FileSystemCode.FS_INITFDFSERROR);
        }
    }
}
